import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/core/api/json_parse.dart';
import 'package:flutter_demo/core/model/category_model.dart';
import 'package:flutter_demo/ui/component/layout.dart';
import 'package:flutter_demo/ui/pages/meal/meal.dart';
import 'package:flutter_demo/ui/shared/size_fit.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Layout("美食广场", HomeContent());
  }
}

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: JsonParse.getCategoryData(),
      builder: (ctx, snapshot) {
        if (!snapshot.hasData) return Center(child: CircularProgressIndicator(),);
        if (snapshot.error != null) return Center(child: Text("请求失败！"),);

        final category = snapshot.data;
        return GridView.builder(
            padding: EdgeInsets.all(setPx(20)),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: setPx(20),
                mainAxisSpacing: setPx(20),
                childAspectRatio: 1.5
            ),
            itemCount: category.length,
            itemBuilder: (ctx, index) {
              return CategoryItem(category[index]);
            }
        );
      },
    );
  }
}

class CategoryItem extends StatelessWidget {
  final CategoryModel item;

  CategoryItem(this.item);

  @override
  Widget build(BuildContext context) {
    final bgColor = item.cColor;

    return GestureDetector(
      onTap: () {
        Navigator.of(context).pushNamed(MealPage.name, arguments: item);
      },
      child: Container(
        decoration: BoxDecoration(
          color: bgColor,
          borderRadius: BorderRadius.circular(12),
          gradient: LinearGradient(
            colors: [
              bgColor.withOpacity(.5),
              bgColor
            ]
          )
        ),
        alignment: Alignment.center,
        child: Text(
          item.title,
          style: Theme.of(context).textTheme.headline1.copyWith(
            fontWeight: FontWeight.bold
          ),
        ),
      ),
    );
  }
}
